package com.sdkj.fixed.asset.system.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.system.in_vo.DicEntityId;
import com.sdkj.fixed.asset.api.system.out_vo.DictionaryResult;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.pojo.system.DictionaryEntity;
import com.sdkj.fixed.asset.pojo.system.DictionaryType;
import com.sdkj.fixed.asset.system.mapper.DictionaryEntityMapper;
import com.sdkj.fixed.asset.system.mapper.DictionaryTypeMapper;
import com.sdkj.fixed.asset.system.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @ClassName dictionaryTypeService
 * @Description 数据字典
 * @Author 张欣
 * @Date 2020/7/21 16:25
 */
@Service
public class DictionaryTypeService extends BaseService<DictionaryType> {
    @Autowired
    private DictionaryTypeMapper dictionaryTypeMapper;
    @Autowired
    private DictionaryEntityMapper dictionaryEntityMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public BaseMapper getMapper() {
        return dictionaryTypeMapper;
    }

    /**
     * 新增数据字典项
     * @param entity
     */
    @Transactional(rollbackFor = Exception.class)
    public void addDicEntity(DictionaryType entity){
        //父项
        DictionaryEntity dictionaryEntity = dictionaryEntityMapper.selectByPrimaryKey(entity.getSdeId());
        if(dictionaryEntity == null || dictionaryEntity.getState() == 2){
            throw new LogicException("数据字典不存在");
        }
        //校验value唯一性
        validateValue(entity.getValue(),"",entity.getSdeId());
        entity.setCtime(DateUtil.now());
        entity.setEtime(DateUtil.now());
        entity.setState(1);
        dictionaryTypeMapper.insertSelective(entity);
        //存放数据字典
        String code = dictionaryEntity.getCode();
        //是否存在
        List dics = null;
        Object exit = redisUtil.hget("dic", code);
        DictionaryResult dic = new DictionaryResult();
        if(exit == null){
             dics = new ArrayList();

        }else{
            dics = (List)exit;
        }
        dic.setName(entity.getName());
        dic.setValue(entity.getValue());
        dic.setSort(Integer.parseInt(entity.getSort()));
        dics.add(dic);
        redisUtil.hset("dic",code,dics);


    }
    private void validateValue(String value,String id,String dicId){
        Example example =new Example(DictionaryType.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("value",value);
        criteria.andEqualTo("state",1);
        criteria.andEqualTo("sdeId",dicId);
        if(StrUtil.isNotBlank(id)){
            criteria.andNotEqualTo("id",id);
        }
        List<DictionaryType> dictionaryEntities = dictionaryTypeMapper.selectByExample(example);
        if(dictionaryEntities.size() > 0){
            throw new LogicException("数据字典项已存在");
        }
    }

    /**
     * 修改
     * @param entity
     */
    @Transactional(rollbackFor = Exception.class)
    public void editDicEntity(DictionaryType entity){
        DictionaryType dictionaryType = dictionaryTypeMapper.selectByPrimaryKey(entity.getId());
        if(dictionaryType == null || dictionaryType.getState() == 2){
            throw new LogicException("数据字典项不存在");
        }
        //父项
        DictionaryEntity dictionaryEntity = dictionaryEntityMapper.selectByPrimaryKey(dictionaryType.getSdeId());
        if(dictionaryEntity == null || dictionaryEntity.getState() == 2){
            throw new LogicException("数据字典不存在");
        }

        String name = dictionaryType.getName();
        String sort = dictionaryType.getSort();

        //校验code唯一性
        //validateCode(entity.getCode(),entity.getCode());
        dictionaryType.setEuser(entity.getEuser());
        dictionaryType.setName(entity.getName());
        dictionaryType.setSort(entity.getSort());
        dictionaryType.setComments(entity.getComments());
        dictionaryType.setEtime(DateUtil.now());
        dictionaryTypeMapper.updateByPrimaryKey(dictionaryType);
        if(!name.equals(entity.getName()) || !sort.equals(entity.getSort())){
            String code = dictionaryEntity.getCode();
            //是否存在
            List dics = null;
            Object exit = redisUtil.hget("dic", code);
            dics = (List)exit;
            for(Object dic : dics ){
                DictionaryResult dictionaryResult = (DictionaryResult) dic;
               if(dictionaryResult.getValue().equals(entity.getValue())){
                   dictionaryResult.setName(entity.getName());
                   dictionaryResult.setSort(Integer.parseInt(entity.getSort()));
                   break;
               }
            }

            redisUtil.hset("dic",code,dics);
        }

    }

    /**
     * 删除
     * @param entity
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteDic(DictionaryType entity){

        DictionaryType dictionaryType = dictionaryTypeMapper.selectByPrimaryKey(entity.getId());
        if(dictionaryType == null || dictionaryType.getState() == 2){
            throw new LogicException("数据字典项不存在");
        }
        //父项
        DictionaryEntity dictionaryEntity = dictionaryEntityMapper.selectByPrimaryKey(dictionaryType.getSdeId());
        if(dictionaryEntity == null || dictionaryEntity.getState() == 2){
            throw new LogicException("数据字典不存在");
        }
        DictionaryType dictionaryType1 = new DictionaryType();
        dictionaryType1.setId(entity.getId());
        dictionaryType1.setState(2);
        dictionaryType1.setEuser(entity.getEuser());
        dictionaryType1.setEtime(DateUtil.now());
        dictionaryTypeMapper.updateByPrimaryKeySelective(dictionaryType1 );
        String code = dictionaryEntity.getCode();
        //是否存在
        List dics = null;
        Object exit = redisUtil.hget("dic", code);
        dics = (List)exit;
        for(Object dic : dics ){
            DictionaryResult dictionaryResult = (DictionaryResult) dic;
            if(dictionaryResult.getValue().equals(dictionaryType.getValue())){
                dics.remove(dic);
                break;
            }
        }

        redisUtil.hset("dic",code,dics);
    }
    public List<DictionaryType> getDiactionaryList(PageParams<DicEntityId> params){
        Example example = new Example(DictionaryType.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state",1);
        criteria.andEqualTo("sdeId",params.getParams().getDicEntityId());
        example.setOrderByClause("ctime DESC");
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<DictionaryType> dictionaryTypes = dictionaryTypeMapper.selectByExample(example);
        return dictionaryTypes;
    }
    public List<DictionaryResult> getDicByCode(String code){
        Object exit = redisUtil.hget("dic", code);
        if(exit == null){
            return new ArrayList<>();
        }
        List<DictionaryResult> result =  (List<DictionaryResult>) exit;

        Comparator<DictionaryResult> netTypeComparator = new Comparator<DictionaryResult>() {
            @Override
            public int compare(DictionaryResult o1, DictionaryResult o2) {
                if(o1.getSort() == null){
                    o1.setSort(1);
                }
                if(o2.getSort() == null){
                    o2.setSort(1);
                }
                if (o1.getSort() > o2.getSort() ){
                    return 1;
                }
                if (o1.getSort().equals(o2.getSort())) {
                    return 0;
                }
                return -1;
            }
        };

        Collections.sort(result,netTypeComparator);
        return result;
    }
    public Map<String, String> getDicValueByCode(String code) {
        List<DictionaryResult> results = (List<DictionaryResult>)redisUtil.hget("dic",code);
        Map<String,String> dicMap = new HashMap<>();
        for (DictionaryResult result : results){
            // Dictionary dictionary = JSONObject.toJavaObject(result,Dictionary.class);
            dicMap.put( result.getValue(),result.getName());
        }
        return dicMap;

    }
}
